/***
 * @desc:订单处理搜索区域地址选择弹框
 * @author：elvis
 * @reference src\views\StockManage\Outbound\component\SelectAddress.jsx
 */

import React, { useEffect, useState } from "react";
import { Checkbox, Empty, Select, Button, Divider, message, Popconfirm } from "antd";
import { findIndex, cloneDeep, find, forEach } from "lodash";
import IconFont from "@/components/IconFont";
import CommonLoading from "@/components/CommonLoading";
import { getAllArea } from "@/services/common";
// import { queryCommonuseaddressList, addCommonuseaddress, delCommonuseaddress } from "../service";
import styles from "./index.module.less";

export default ({ handleOk, addressData = [], onChange, value }) => {
	//省市区信息
	const [data, setData] = useState([]);
	//当前展示的省id
	const [provinceId, setProvinceId] = useState(undefined);
	const [cityId, setCityId] = useState(undefined);
	//地址选择弹框
	const [visible, setVisible] = useState(false);

	//添加常用地址弹窗
	// const [addVisible, setAddVisible] = useState(false);

	//选择的数据
	const [selectData, setSelectData] = useState(cloneDeep(addressData));

	//常用地址
	const [commonAddressList, setCommonAddressList] = useState([]);
	const [loading, setLoading] = useState(false);

	useEffect(() => {
		if (data.length === 0) getAreaData();
		if (selectData.length > 0) {
			setProvinceId(selectData[0].id);
		} else {
			// if (data.length > 0) {
			// 	setProvinceId(data[0].id);
			// }
		}
	}, []);

	useEffect(() => {
		// console.log("data 数据发生变化", data);
	}, [data]);
	useEffect(() => {
		if (visible) {
			// getCommonAddressList();
		}
	}, [visible]);
	useEffect(() => {
		if (!value) {
			setSelectData([]);
			setProvinceId(undefined);
		}
	}, [value]);
	// //获取常用地址列表
	// const getCommonAddressList = async () => {
	// 	setLoading(true);
	// 	const { success, data = {} } = await queryCommonuseaddressList({
	// 		current: 1,
	// 		size: 100
	// 	});
	// 	const { records = [] } = data;
	// 	const arr = [];
	// 	records.forEach(item => {
	// 		arr.push({
	// 			...item,
	// 			delOpen: false
	// 		});
	// 	});
	// 	if (success) {
	// 		setCommonAddressList(arr);
	// 	}
	// 	setLoading(false);
	// };

	//获取省市区地址信息
	const getAreaData = async () => {
		const { data, success } = await getAllArea();
		if (success) {
			// console.log("获取地址数据", data);
			setData(data);
		}
	};

	//选择省份
	const handleSelectProvince = (e, id) => {
		if (id > 100) {
			message.warning("暂不支持该区域");
			return;
		}
		let checked = e.target.checked;
		if (checked) {
			//全选市
			const obj = find(data, ["id", id]);
			const arr = cloneDeep(selectData);
			const index = findIndex(arr, ["id", id]);
			if (index > -1) {
				arr[index] = obj;
			} else {
				arr.push(obj);
			}
			setSelectData(arr);
			handleClickProvince(id);
		} else {
			const arr = cloneDeep(selectData);
			const index = findIndex(arr, ["id", id]);
			arr.splice(index, 1);
			setSelectData(arr);
			handleClickProvince(id);
		}
	};
	//选择市
	const handleSelectCity = (e, id) => {
		let checked = e.target.checked;
		if (checked) {
			//全选区
			//查询到省
			const obj = find(data, ["id", provinceId]);
			//查询到市
			const obj1 = find(obj.childs, ["id", id]);

			const index1 = findIndex(selectData, ["id", provinceId]);
			if (index1 > -1) {
				//如果已选列表包含当前省
				const index2 = findIndex(selectData[index1].childs, ["id", id]);
				const arr = cloneDeep(selectData);
				if (index2 > -1) {
					//如果已选包含当前市
					arr[index1].childs[index2] = obj1;
				} else {
					arr[index1].childs.push(obj1);
				}
				setSelectData(arr);
			} else {
				const arr = cloneDeep(selectData);
				const arr1 = [];
				arr1.push(obj1);
				const obj = {
					id: provinceId,
					name: find(data, ["id", provinceId]).name,
					childs: arr1
				};
				arr.push(obj);
				setSelectData(arr);
			}
		} else {
			//取消全选
			const arr = cloneDeep(selectData);
			const index1 = findIndex(selectData, ["id", provinceId]);
			const index2 = findIndex(selectData[index1].childs, ["id", id]);
			arr[index1].childs.splice(index2, 1);
			setSelectData(arr);
		}
		handleClickCity(id);
	};
	//选择区
	const handleSelectArea = (e, id) => {
		let checked = e.target.checked;
		if (checked) {
			//选择
			const index = findIndex(selectData, ["id", provinceId]);
			if (index > -1) {
				//已选列表包含当前省
				const index1 = findIndex(selectData[index].childs, ["id", cityId]);
				if (index1 > -1) {
					//已选列表包含当前市
					const obj = {
						id: id
					};
					const arr = cloneDeep(selectData);
					arr[index].childs[index1].childs.push(obj);
					setSelectData(arr);
				} else {
					const arr = [];
					arr.push({ id: id });
					const obj = {
						id: cityId,
						childs: arr
					};
					const list = cloneDeep(selectData);
					list[index].childs.push(obj);
					setSelectData(list);
				}
			} else {
				const arr = [];
				arr.push({ id });
				const obj = {
					id: cityId,
					childs: arr
				};
				const arr1 = [];
				arr1.push(obj);
				const obj1 = {
					id: provinceId,
					name: find(data, ["id", provinceId]).name,
					childs: arr1
				};
				const list = cloneDeep(selectData);
				list.push(obj1);
				setSelectData(list);
			}
		} else {
			//取消选择
			const index1 = findIndex(selectData, ["id", provinceId]);
			const index2 = findIndex(selectData[index1].childs, ["id", cityId]);
			const index3 = findIndex(selectData[index1].childs[index2].childs, ["id", id]);
			const arr = cloneDeep(selectData);
			arr[index1].childs[index2].childs.splice(index3, 1);
			setSelectData(arr);
		}
	};

	//查看省份
	const handleClickProvince = id => {
		if (id == provinceId) {
			return;
		}
		if (id > 100) {
			message.warning("暂不支持该区域");
			return;
		}
		const arr = find(data, ["id", id]).childs;
		setProvinceId(id);
		setCityId(arr[0].id);
	};
	//查看市
	const handleClickCity = id => {
		if (id == cityId) {
			return;
		}
		setCityId(id);
	};

	//判断省是否全选
	const getProvinceChecked = id => {
		const index = findIndex(selectData, ["id", id]);
		if (index > -1) {
			const arr1 = find(data, ["id", id]).childs;
			const arr2 = selectData[index].childs;
			if (arr1.length == arr2.length) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	};

	//判断市是否选择
	const getCityChecked = id => {
		const index1 = findIndex(selectData, ["id", provinceId]);
		if (index1 == -1) {
			return false;
		}
		const arr = find(selectData, ["id", provinceId]).childs;
		const index = findIndex(arr, ["id", id]);
		if (index > -1) {
			const arr1 = find(find(data, ["id", provinceId]).childs, ["id", id]).childs;
			const arr2 = find(arr, ["id", id]).childs;
			if (arr1.length == arr2.length) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	};

	//判断区是否是选择
	const getAreaChecked = id => {
		//首先判断是否是否有该省份
		const index1 = findIndex(selectData, ["id", provinceId]);
		if (index1 == -1) {
			return false;
		} else {
			//其次判断是否有该市区
			const index2 = findIndex(selectData[index1].childs, ["id", cityId]);
			if (index2 == -1) {
				return false;
			} else {
				const index3 = findIndex(selectData[index1].childs[index2].childs, ["id", id]);
				if (index3 > -1) {
					return true;
				}
				return false;
			}
		}
	};

	//显示市是否全选
	const handleSelectAllCity = id => {
		const cityData = find(selectData, ["id", provinceId]);
		if (cityData) {
			let num2 = find(cityData.childs, ["id", id]) ? find(cityData.childs, ["id", id]).childs.length : undefined;
			if (num2) {
				const cityData1 = find(data, ["id", provinceId]).childs;
				let num1 = find(cityData1, ["id", id]).childs.length;
				if (num2 < num1) {
					return true;
				}
				return false;
			}
		} else {
			return false;
		}
	};

	//渲染市列表
	const renderCity = () => {
		if (provinceId) {
			const arr = find(data, ["id", provinceId]).childs;
			return (
				<div style={{ width: "260px" }}>
					{arr.map(v => (
						<span style={{ margin: "2px 8px", display: "inline-block" }} key={v.id}>
							<span className="flex-row-center">
								<Checkbox
									indeterminate={handleSelectAllCity(v.id)}
									checked={getCityChecked(v.id)}
									onChange={e => handleSelectCity(e, v.id)}
								/>
								<span
									className={v.id == cityId ? styles.select : styles.normal}
									style={{ marginLeft: 8 }}
									key={v.id}
									onClick={() => handleClickCity(v.id)}
								>
									{v.name}
									{getCityNum(v.id)}
								</span>
							</span>
						</span>
					))}
				</div>
			);
		} else {
			return (
				<div style={{ height: "250px" }}>
					<Empty description="请选择省份" />
				</div>
			);
		}
	};

	//渲染区域列表
	const renderArea = () => {
		if (cityId) {
			const arr = find(data, ["id", provinceId])?.childs;
			const arr1 = find(arr, ["id", cityId])?.childs;
			return (
				<div style={{ flex: 1, lineHeight: "32px", overflow: "auto" }}>
					{arr1?.map(v => (
						<span key={v.id} style={{ margin: "0 8px" }}>
							<Checkbox checked={getAreaChecked(v.id)} onClick={e => handleSelectArea(e, v.id)}>
								{v.name}
							</Checkbox>
						</span>
					))}
				</div>
			);
		} else {
			return (
				<div>
					<Empty description="请选择市" />
				</div>
			);
		}
	};

	//计算该省份选择市的数量
	const getProvinceNum = id => {
		const obj = find(selectData, ["id", id]);
		if (obj) {
			return `（${obj.childs.length}）`;
		}
		return `（0）`;
	};

	//计算该城市选择区的数量
	const getCityNum = id => {
		const obj = find(selectData, ["id", provinceId]);
		if (obj) {
			const obj1 = find(obj.childs, ["id", id]);
			if (obj1) {
				return `（${obj1.childs.length}）`;
			}
			return `（0）`;
		}
		return `（0）`;
	};

	//显示是否全选
	const handleSelectAll = id => {
		let num2 = find(selectData, ["id", id]) ? find(selectData, ["id", id]).childs.length : undefined;
		if (num2) {
			let num1 = find(data, ["id", id]).childs.length;
			if (num2 < num1) {
				return true;
			}
			return false;
		}
		return false;
	};

	const handleVisibleChange = val => {
		const index = findIndex(commonAddressList, ["delOpen", true]);
		if (index == -1) {
			setVisible(val);
		}
	};

	// 设置常用地址
	const setCommonAddresses = () => {
		// console.log("设置常用地址");
		// console.log("selectData", selectData);
		const arr = cloneDeep(commonAddressList);
		setCommonAddressList([...arr, selectData]);
		// const arr = [];
		// selectData.map(v => {
		// 	v.childs.map(k => {
		// 		arr.push(k.id);
		// 	});
		// });
		// if (arr.length === 0) {
		// 	message.warning("请先选择地址");
		// 	return;
		// } else {
		// 	setCommonAddressList(arr);
		// }
	};

	//删除常用地址
	const deleteCommonAddress = async (e, index) => {
		// console.log("删除常用地址", index);
		// e.stopPropagation();
		// setLoading(true);
		// const arr = cloneDeep(commonAddressList);
		// arr.splice(index, 1);
		// setCommonAddressList(arr);
		// // const { success, msg } = await delCommonuseaddress({
		// // 	ids: id
		// // });
		// // if (success) {
		// // 	message.success(msg);
		// // 	// getCommonAddressList();
		// // }
		// setLoading(false);
	};

	//打开/关闭删除确定弹窗
	const handleOpenAddress = (index, bool) => {
		// console.log("handleOpenAddress");
		// const arr = cloneDeep(commonAddressList);
		// // if (bool) {
		// // 	arr.splice(index, 1);
		// // }
		// // setCommonAddressList(arr);
		// arr.map((item, ind) => {
		// 	if (ind == index) {
		// 		item.delOpen = bool;
		// 	}
		// });
	};

	//选择常用地址
	const selectCommonAddress = val => {
		// console.log("选择常用地址", val);
		// const addressList = val.addressJson ? JSON.parse(val.addressJson) : [];
		// const arr = [];
		// addressList.forEach(item => {
		// 	arr.push({
		// 		id: item.id,
		// 		childs: item.childs.map(z => {
		// 			return { id: z };
		// 		})
		// 	});
		// });
		// setProvinceId(addressList[0].id);
		// setSelectData(arr);
	};

	const onOk = () => {
		if (selectData.length > 0) {
			// console.log("selectData", selectData);
			const arr = [];
			selectData.forEach(item => {
				item.childs.forEach(it => {
					it.childs.forEach(e => {
						arr.push(e.id);
					});
				});
			});
			// selectData.map(v => {
			// 	v.childs.map(k => {
			// 		// arr.push(k.id);
			// 	});
			// });
			handleOk(arr, selectData);
		} else {
			handleOk(undefined, []);
		}
		setVisible(false);
	};

	const onReset = () => {
		handleOk(undefined, []);
		setSelectData([]);
		setVisible(false);
	};

	//添加常用地址
	// const AddCommonAddressProps = {
	// 	visible: addVisible,
	// 	data,
	// 	handleCancel() {
	// 		setAddVisible(false);
	// 	},
	// 	handleOk() {
	// 		getCommonAddressList();
	// 		setAddVisible(false);
	// 	}
	// };

	return (
		<span className={styles.addressSelect}>
			<Select
				placeholder={selectData.length > 0 ? "点击查看选择详情" : "请选择地址"}
				optionFilterProp="label"
				allowClear
				dropdownStyle={{
					zIndex: 800
				}}
				onDropdownVisibleChange={handleVisibleChange}
				open={visible}
				dropdownMatchSelectWidth={990}
				dropdownRender={() => {
					if (data.length <= 0) {
						return <Empty description="未获取到省市区信息" />;
					}
					return (
						<div style={{ padding: 12 }}>
							<div className="flex">
								<div style={{ width: "380px", overflow: "auto" }}>
									<h3 style={{ marginBottom: "8px" }}>省列表：</h3>
									<div style={{ display: "flex", flexWrap: "wrap" }}>
										{data.map(v => (
											<div key={v.id} className="flex-row-center" style={{ width: "112px", margin: "2px 4px" }}>
												<Checkbox
													indeterminate={handleSelectAll(v.id)}
													checked={getProvinceChecked(v.id)}
													onChange={e => handleSelectProvince(e, v.id)}
												/>
												<span
													className={v.id == provinceId ? "common-color2" : "common-color4 common-color2"}
													style={{ marginLeft: 8 }}
													onClick={() => handleClickProvince(v.id)}
													key={v.id}
												>
													{v.name}
													{getProvinceNum(v.id)}
												</span>
											</div>
										))}
									</div>
								</div>
								<Divider type="vertical" style={{ height: "345px" }} />
								<div className="flex" style={{ flex: 1 }}>
									<div>
										<h3 style={{ marginBottom: "8px" }}>市列表：</h3>
										{renderCity()}
									</div>
									<Divider type="vertical" style={{ height: "345px" }} />
									<div>
										<h3>区列表：</h3>
										{renderArea()}
									</div>
								</div>
							</div>
							<div className={styles.commonAddressList}>
								{commonAddressList.map((z, index) => (
									<div key={index} className={styles.pointsDel}>
										<span onClick={() => selectCommonAddress(z)}>常用地址{index + 1}</span>
										<Popconfirm
											title="确定删除该常用地址吗?"
											onConfirm={e => deleteCommonAddress(e, index)}
											onCancel={() => {
												handleOpenAddress(index, false);
											}}
											okText="确定"
											cancelText="取消"
											open={z.delOpen}
										>
											<span
												onClick={() => {
													handleOpenAddress(index, true);
												}}
											>
												<IconFont className={styles.delIcon} type="iconclose" />
											</span>
										</Popconfirm>
									</div>
								))}
							</div>
							<div style={{ textAlign: "right", marginTop: "12px" }}>
								<Button
									disabled={commonAddressList.length === 4}
									onClick={() => setCommonAddresses()}
									style={{ marginRight: "12px" }}
								>
									保存为常用地址({commonAddressList.length}/4)
								</Button>
								<Button onClick={onOk} type="primary" style={{ marginRight: "12px" }}>
									确定
								</Button>
								<Button onClick={onReset}>重置</Button>
							</div>
							<CommonLoading loading={loading} />
						</div>
					);
				}}
				onChange={onChange}
			/>
		</span>
	);
};
